#!/bin/bash
set -euo pipefail

# 配置
LOG_DIR="./logs"
LOG_FILE="${LOG_DIR}/resource_monitor.log"
MAX_LOG_FILE_SIZE=$((50 * 1024 * 1024))  # 单个日志最大 50MB
MAX_TOTAL_LOG_SIZE=$((100 * 1024 * 1024))  # 所有日志最大 100M
INTERVAL=5  # 每隔多少秒采集一次

mkdir -p "$LOG_DIR"

# 获取资源信息
collect_info() {
    {
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] Resource Snapshot"
        echo "CPU Usage:"
        top -bn1 | grep "Cpu(s)" | sed 's/^/    /'
        echo "Memory Usage:"
        free -h | sed 's/^/    /'
        echo "Disk Usage:"
        df -h | grep '^/' | sed 's/^/    /'
	echo "Proc Meminfo"
	cat /proc/meminfo
        echo "----------------------------------------"
    } >> "$LOG_FILE"
}

# 压缩当前日志
rotate_log() {
    local timestamp
    timestamp=$(date '+%Y%m%d_%H%M%S')
    gzip -c "$LOG_FILE" > "${LOG_FILE}.${timestamp}.gz"
    : > "$LOG_FILE"
}

# 清理旧日志，保持总大小不超过1GB
cleanup_old_logs() {
    local total_size
    total_size=$(du -cb "$LOG_DIR"/* | grep total | awk '{print $1}')
    while (( total_size > MAX_TOTAL_LOG_SIZE )); do
        # 找最老的 .gz 文件删除
        oldest_file=$(ls -1t "$LOG_DIR"/resource_monitor.log.*.gz 2>/dev/null | tail -n 1)
        if [[ -n "$oldest_file" ]]; then
            echo "[INFO] Deleting old log: $oldest_file" >> "$LOG_FILE"
            rm -f "$oldest_file"
        else
            break  # 没有压缩日志可删
        fi
        total_size=$(du -cb "$LOG_DIR"/* | grep total | awk '{print $1}')
    done
}

# 主循环
echo "[INFO] Monitoring started at $(date '+%Y-%m-%d %H:%M:%S')" >> "$LOG_FILE"
while true; do
    collect_info

    current_size=$(stat -c %s "$LOG_FILE")
    if (( current_size >= MAX_LOG_FILE_SIZE )); then
        echo "[INFO] Rotating log at $(date '+%Y-%m-%d %H:%M:%S')" >> "$LOG_FILE"
        rotate_log
        cleanup_old_logs
        echo "[INFO] New log started at $(date '+%Y-%m-%d %H:%M:%S')" >> "$LOG_FILE"
    fi

    sleep "$INTERVAL"
done

#使用方式，文件保存到设备指定目录后，在目录下执行 nohup bash resource_monitor.sh &
